// 权限管理工具函数

// 用户角色类型
export type UserRole = 'admin' | 'user';

// 需要管理员权限的路由
export const ADMIN_ROUTES = [
  '/message', 
  '/shopping', 
  '/anli', 
  '/Yuyue', 
  '/Fuzhen', 
  '/Search', 
  '/DoctorDetail', 
  '/MedicineDetail', 
  '/YaoDetail',
  '/SocoDetail', 
  '/City', 
  '/GuaSearch', 
  '/Guahao', 
  '/OrderDetail',
  '/Teme', 
  '/RiskDisclosure', 
  '/NewOrder', 
  '/ArtDetail',
  '/talkDoctor'
];

// 普通用户可访问的路由
export const USER_ROUTES = [
  '/index', 
  '/order', 
  '/Wenzhen', 
  '/set'
];

// 管理员手机号
export const ADMIN_PHONE = '18332266897';

/**
 * 获取用户角色
 */
export const getUserRole = (): UserRole => {
  const phone = localStorage.getItem('userPhone');
  return phone === ADMIN_PHONE ? 'admin' : 'user';
};

/**
 * 获取用户手机号
 */
export const getUserPhone = (): string | null => {
  return localStorage.getItem('userPhone');
};

/**
 * 检查用户是否为管理员
 */
export const isAdmin = (): boolean => {
  return getUserRole() === 'admin';
};

/**
 * 检查用户是否为普通用户
 */
export const isUser = (): boolean => {
  return getUserRole() === 'user';
};

/**
 * 检查页面访问权限
 */
export const hasPagePermission = (path: string): boolean => {
  const role = getUserRole();
  
  // 管理员可以访问所有页面
  if (role === 'admin') {
    return true;
  }
  
  // 普通用户只能访问允许的路由
  return USER_ROUTES.some(route => path.startsWith(route));
};

/**
 * 检查功能权限
 */
export const hasFeaturePermission = (feature: string): boolean => {
  const role = getUserRole();
  
  // 管理员拥有所有功能权限
  if (role === 'admin') {
    return true;
  }
  
  // 普通用户的功能权限
  const userFeatures = ['极速问诊', '我的', '首页'];
  return userFeatures.includes(feature);
};

/**
 * 设置用户信息
 */
export const setUserInfo = (phone: string, token: string): void => {
  localStorage.setItem('userPhone', phone);
  localStorage.setItem('token', token);
  localStorage.setItem('userRole', phone === ADMIN_PHONE ? 'admin' : 'user');
};

/**
 * 清除用户信息
 */
export const clearUserInfo = (): void => {
  localStorage.removeItem('userPhone');
  localStorage.removeItem('token');
  localStorage.removeItem('userRole');
};

/**
 * 获取权限提示信息
 */
export const getPermissionMessage = (feature: string): string => {
  return `您当前为普通用户，无法访问${feature}功能，请联系管理员获取权限`;
};
